package com.wnzt.baszh.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wnzt.baszh.util.common.GlobalStatic;

public class SecurityInterceptor implements HandlerInterceptor {
    // 不需要拦截的资源
    private List<String> excludeUrls;

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());
        // 如果要访问的资源是不需要验证的
        if (excludeUrls.contains(url)||url.indexOf("/ws/")!=-1) {// ws接口地址不拦截  -lvtangwei 2017.05.23
            return true;
        }
        // 获得Session
        Object obj = request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        // 如果没有登录或登录超时
        if (null == obj || url.equals("/")) {
            request.setAttribute("msg", "您还没有登录或登录已超时，请重新登录，然后再刷新本功能！");
            // request.getRequestDispatcher("/login").forward(request,
            // response);
            response.sendRedirect(contextPath + "/login");
            return false;
        }
        return true;
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    public List<String> getExcludeUrls() {
        return excludeUrls;
    }

    public void setExcludeUrls(List<String> excludeUrls) {
        this.excludeUrls = excludeUrls;
    }
}
